package com.wthink.hzgj.util.adapter

import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import kotlin.properties.Delegates

abstract class AutoUpdatableAdapter<T : BaseViewHolder, V>(val compare: (o: V, n: V) -> Boolean) :
    BaseAdapter<T>() {

    override var items: List<Any> by Delegates.observable(emptyList())
    { _, old, new ->
        @Suppress("UNCHECKED_CAST")
        autoNotify(old as List<V>, new as List<V>, compare)
    }

    override fun update(items: List<Any>) {
        this.items = items
    }

        fun RecyclerView.Adapter<*>.autoNotify(
            old: List<V>,
            new: List<V>,
            compare: (V, V) -> Boolean
        ) {
            val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() {

                override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                    return compare(old[oldItemPosition], new[newItemPosition])
                }

                override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                    return old[oldItemPosition] == new[newItemPosition]
                }

                override fun getOldListSize() = old.size

                override fun getNewListSize() = new.size
            })

            diff.dispatchUpdatesTo(this)
        }
}